<?php

/**
 * @author      Nguyen Duc Thuan<me@ndthuan.com>
 * @copyright   Nguyen Duc Thuan <me@ndthuan.com>
 */
class Fete_Route_Regex extends Fete_Route
{
    protected $_reverseUrl = null;

    public function __construct($condition, $params = array()
        , $reverseUrl = null)
    {
        $this->_reverseUrl = null !== $reverseUrl ? $reverseUrl : $condition;

        parent::__construct($condition, $params);
    }

    public function match($query)
    {
        if (preg_match('#^' . str_replace('#', '\#', $this->_condition) . '$#'
            , $query, $matches)) {
            foreach ($this->_params as $key => $value)
            {
                if ('$' === $value{0}) {
                    $this->_params[$key] = $matches[substr($value, 1)];
                }
            }

            return true;
        }

        return false;
    }

    public function getLink($params = array())
    {
        $link = $this->_reverseUrl;

        foreach ($params as $key => $value)
        {
            $link = str_replace('%' . $key, $value, $link);
        }

        return $link;
    }
}